<template>
  <div class="app-container">

    <el-card v-loading="loading">
      <div slot="header" class="clearfix">
        <span>活动详情</span>
        <el-button @click="back" style="float: right;">返回</el-button>
        <el-button type="primary" class="fm-button" style="float: right;margin-right: 20px" @click="submitForm">保 存</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入活动编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="报名开始" prop="startTime">
                            <el-date-picker id="date-picker-0"
                              v-model="form.startTime" placeholder="选择开始时间"
                              type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
<!--              <el-date-picker-->
<!--                v-model="form.dates"-->
<!--                type="daterange"-->
<!--                range-separator="至"-->
<!--                value-format="yyyy-MM-dd"-->
<!--                start-placeholder="开始日期"-->
<!--                end-placeholder="结束日期">-->
<!--              </el-date-picker>-->
            </el-form-item>

          </el-col>
            <el-col :span="12">
            <el-form-item label="报名结束" prop="activityEndTime">
              <el-date-picker id="date-picker-1" v-model="form.activityEndTime" placeholder="选择结束时间" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" >
              </el-date-picker>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="举办时间" prop="activityStartTime">
              <!-- <el-date-picker
                 v-model="form.dates"
                 type="daterange"
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期">
               </el-date-picker>
             </el-form-item>-->

              <el-date-picker
                v-model="form.activityStartTime" placeholder="选择开始时间"
                type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="封面" prop="cover">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                list-type="picture-card"
                :action="url"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :limit="1"
                :file-list="picList"
                :headers="headers"
                :before-upload="checkUpload">
                <img v-if="files.path" :src="base_url+files.path" class="avatar" width="100px" height="100px">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="背景音乐" v-if="false">
              <el-upload
                class="upload-demo"
                :headers="headers" accept=".mp4,.wav"
                :action="base_url + '/common/upload/media'"
                :on-success="handleSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload" :on-error="handleError" :on-exceed="handleExceed"
                multiple
                :limit="1"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
        </el-form-item>
            <el-col :span="12">
            <div style="display: flex;align-items: center;" v-if="fileList.length>0">
              试听： <audio :src="fileList[0].url"  controls="" ></audio>
            </div>
          </el-col>
            </el-col>
          </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="type">
              <el-select v-model="form.type">
                <el-option label="企业" value="0"/>
                <el-option label="个人" value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == 0">
            <el-form-item label="企业" prop="corps">
              <el-select multiple v-model="form.corpIds">
                <el-option v-for="(item,index) in corpList" :key="index" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可用权益" prop="isMember">
              <el-select v-model="form.isMember">
                <el-option label="是" value="0" />
                <el-option label="否" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名费" prop="fee">
              <el-input v-model="form.fee" placeholder="请输入报名费" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="男生数" prop="maleTotal">
              <el-input-number v-model="form.maleTotal" placeholder="请输入男生数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="女生数" prop="maleTotal">
              <el-input-number v-model="form.femaleTotal" placeholder="请输入女生数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="位置" prop="latitude">
              <el-button size="medium" @click="mapDialog=true">点击选择坐标</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="维度" prop="latitude">
              <el-input v-model="form.latitude" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入站点详细地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="范围m" prop="signRanger">
              <el-input v-model="form.signRanger" placeholder="请输入站点签到范围"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="内容">
          <vue-ueditor-wrap v-model="form.content" :config="myConfig" ></vue-ueditor-wrap>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 地图定位弹框 -->
    <el-dialog title="获取地图坐标" :visible.sync="mapDialog" v-if="mapDialog" width="1000px" append-to-body>
      <GetCoordinate ref="map"></GetCoordinate>
      <span slot="footer">
    <el-button @click="mapDialog = false" size="mini">取 消</el-button>
    <el-button @click="getCoordinate" size="mini" type="primary">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import { listActivity, getActivity, delActivity, addActivity, updateActivity, exportActivity, genActivity } from "@/api/ypp/activity";
  import { listCorp,addActivityCorp } from "@/api/ypp/corp.js";
  import { checkRole } from "@/utils/permission.js";
  import { getToken } from "@/utils/auth";

  import VueUeditorWrap from 'vue-ueditor-wrap';
  import { parseTime,  } from "@/utils/ruoyi";
  import ImageUpload from '@/components/ImageUpload';
  import GetCoordinate from '@/views/components/map/locationMap';
  export default {
    name: "ActivityEdit",
    components: {
      VueUeditorWrap,
      GetCoordinate,
      ImageUpload
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 活动项目表格数据
        activityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          status: undefined,
          deptId: undefined
        },
        // 表单参数
        form: {
          id: undefined,
          name: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          status: "1",
          deptId: undefined,
          content: undefined,
          backgroundMusicPath:undefined,
          code: undefined,
          startTime:undefined,
          activityEndTime: undefined,
          activityStartTime:undefined,
          maleTotal:undefined,
          femaleTotal:undefined,
          isMember:undefined,
          type:undefined,
          corpIds:undefined,
          cover:undefined,
          signRanger:undefined,
          longitude:undefined,
          latitude:undefined,
          address:undefined,
          fee:undefined
        },
        // 表单校验
        rules: {
          name: [
            { required: true, message: "活动名称不能为空", trigger: "blur" }
          ],
          cover:[
            { required:true,message:'请上传活动封面',trigger: "blur"}
          ],
          startTime:[
            { required:true,message:'请选择活动报名开始时间',trigger: "blur"}
          ],
          activityEndTime:[
            { required:true,message:'请选择活动报名结束时间',trigger: "blur"}
          ],
          activityStartTime:[
            { required:true,message:'请选择活动开始时间',trigger: "blur"}
          ],
          isMember:[
            { required:true,message:'请选择活动类型',trigger: "blur"}
          ],
          latitude:[
            { required:true,message:'请选择活动举办地',trigger: "blur"}
          ],
          longitude:[
            { required:true,message:'请选择活动举办地',trigger: "blur"}
          ],
          type:[
            { required:true,message:'请选择是否企业活动',trigger: "blur"}
          ],
          signRanger:[
            { required:true,message:'请输入签到范围',trigger: "blur"}
          ],
          maleTotal:[
            {required:true,message:'请选择男生名额',trigger: "blur"}
          ],
          femaleTotal:[
            {required:true,message:'请选择女生名额',trigger: "blur"}
          ],
          address:[
            {required:true,message:'请输入活动地点',trigger: "blur"}
          ]
        },
        deptOptions:[],
        preview:{
          open:false,
          title:'查看二维码',
          name:'',
          src:''
        },
        id: undefined,
        base_url: process.env.VUE_APP_BASE_API,
        headers: { Authorization: "Bearer " + getToken() },
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 540,
          // 初始容器宽度
          initialFrameWidth: '100%',
          //启用自动保存
          enableAutoSave: true,
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！部署在国外的服务器，如果无法访问，请自备梯子）
          serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId='+this.$store.getters.userInfo.userId,
          // serverUrl:'http://35.201.165.105:8000/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          UEDITOR_HOME_URL: '/ueditor/',
          zIndex: 1
        },
        fileList:[],
        url:process.env.VUE_APP_BASE_API + "/common/upload",
        //图片路径
        files: {path: ''},
        picList:[],
        mapDialog:false,
        corpList:[]
      };
    },
    created() {
      listCorp().then(res=>{
        this.corpList = res.rows
      })
      this.id = this.$route.query.id;
      this.getDicts("ypp_activity_status").then(response => {
        this.statusOptions = response.data;

        if (this.id){
          this.handleUpdate();
        }else {
          this.reset();
          this.loading = false;
        }
      });
    },
    methods: {
      /** 查询活动项目列表 */
      getList() {
        this.loading = true;
        listActivity(this.queryParams).then(response => {
          this.activityList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      deptFormat(row,column){
        var txt = '';
        this.deptOptions.filter(e =>{
          if (e.deptId == row.deptId){
            txt = e.deptName;
            return;
          }
        })
        return txt;
      },
      handleCheckRole(v){
        return checkRole([v]);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          status: "1",
          deptId: undefined,
          content: undefined,
          backgroundMusicPath:undefined,
          code: undefined,
          startTime:undefined,
          activityEndTime: undefined,
          activityStartTime:undefined,
          maleTotal:undefined,
          femaleTotal:undefined,
          isMember:undefined,
          type:undefined,
          corpIds:undefined,
          cover:undefined,
          signRanger:undefined,
          longitude:undefined,
          latitude:undefined,
          address:undefined,
          fee:undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加活动项目";
      },
      getDateString(val){
        if(val && val.length < 12){
          return val + ' 00:00:00';
        }
        return val;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();

        getActivity(this.id).then(response => {
          this.form = response.data;

          if (response.data.backgroundMusicPath) {
            this.fileList = [{
              url :this.base_url + response.data.backgroundMusicPath,
              name: response.data.backgroundMusicName,
              fileName : response.data.backgroundMusicPath
            }];
          }
          if (response.data.cover) {
            this.files.path = response.data.cover;
          }
          this.$refs.upload.clearFiles();
          if(response.data.corpIds){
            let ids = []
            response.data.corpIds.split(',').map(e=>{
              if(e){
                ids.push(Number(e))
              }
            })
            this.form.corpIds = ids
          }
          this.loading = false;
        });
      },
      //查看二维码
      handlePreview(row){
        this.preview.src = undefined;
        this.id = row.id;
        const id = row.id;
        getActivity(id).then(response => {
          var d = response.data;
          this.preview.name = d.name;

          if (d.qrcodePath == null || d.qrcodePath==''){
            genActivity(id).then(res => {
              this.preview.src = d.data;
              this.preview.open = true;
            })
          } else {
            this.preview.src = d.qrcodePath;
            this.preview.open = true;
          }
        });
      },
      gen(){
        let loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        genActivity(this.id).then(res => {
          this.preview.src = res.data;
          loading.close();
        })
      },
      previewClose(){
        this.preview.open = false;
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {

            if (this.fileList.length>0){
              let txt = '';
              this.fileList.filter(e=>{
                if (txt == ''){
                  txt = e.fileName;
                } else {
                  txt +=','+ e.fileName;
                }
              })
              this.form.backgroundMusicPath = txt;
            }
            if (this.picList.length>0){
              let txt = '';
              this.picList.filter(e=>{
                if (txt == ''){
                  txt = e.fileName;
                } else {
                  txt +=','+ e.fileName;
                }
              })
              this.form.cover = txt;
            }
            if(!this.form.startTime){
              this.msgError("请选择活动报名开始时间");
              return;
            }
            if(!this.form.activityEndTime){
              this.msgError("请选择活动报名结束时间");
              return;
            }
            if(!this.form.activityStartTime){
              this.msgError("请选择活动开始时间");
              return;
            }
            if(!this.form.cover){
              this.msgError("请上传封面图");
              return;
            }
            // if(this.form.dates){
            //   this.form.startTime = this.form.dates[0]
            //   this.form.startTime = this.form.dates[1]
            // }
            if(this.form.type == 0 && this.form.corpIds.length==0){
              this.msgError("请选择企业");
              return;
            }
            if(!this.form.isMember){
              this.msgError("请选择能否使用权益");
              return;
            }
            if(!this.form.latitude){
              this.msgError("请选择活动地点");
              return;
            }
            if(!this.form.maleTotal){
              this.msgError("请输入男生名额");
              return;
            }
            if(!this.form.femaleTotal){
              this.msgError("请输入女生名额");
              return;
            }
            if(!this.form.address){
              this.msgError("请输入活动地点");
              return;
            }
            if(!this.form.signRanger){
              this.msgError("请选择签到范围");
              return;
            }

            if (this.form.corpIds&&this.form.corpIds.length>0){
              let txt = '';
              this.form.corpIds.map(e=>{
                if(txt == ''){
                  txt = e
                }else {
                  txt = txt + ',' + e
                }
              })
              this.form.corpIds = txt;
            }

            // if (this.form.dates && this.form.dates.length>1){
            //   var startTime = this.form.dates[0];
            //   var awardEndTime = this.form.dates[1];
            //
            //   this.form.startTime = parseTime(startTime,'{y}-{m}-{d}');
            //   this.form.awardEndTime = parseTime(awardEndTime,'{y}-{m}-{d}');
            // }

            if (this.form.id != undefined) {
              updateActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");

                  setTimeout(res=>{
                    this.back();
                  },500)
                }
              });
            } else {
              addActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");

                  setTimeout(res=>{
                    this.back();
                  },500)
                }
              });
            }
          }
        });
      },
      back(){
        this.$store.dispatch("tagsView/delView", this.$route);  //关闭当前页

        var location = '/ypp/activity';
        var param = {'path':location, name:'Activity' };
        this.$router.push(param)

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除活动项目编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActivity(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有活动项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportActivity(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      },

      handleSuccess(file,fileList){
        console.log('上传成功',file,fileList)
        if (typeof fileList == "array" ){
          fileList.filter(e=>{
            e.url = e.response.url;
            e.fileName = e.response.fileName;
          })
          this.fileList = fileList;
        } else {
          fileList.url = fileList.response.url;
          fileList.fileName = fileList.response.fileName;
          this.fileList = [fileList];
        }
      },
      handleError(e){
        console.log(e)
      },
      handleExceed(e){
        console.log(e)
        this.$message({
          message: '请先删除已有文件后，再进行上传',
          type: 'error'
        });
      },
      beforeRemove(file, fileList) {
        console.log('移除',file,fileList);
        this.fileList = [];
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
        return;
      },
      beforeUpload(file) {
        var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
        const extension = testmsg === 'mp3'
        const extension2 = testmsg === 'wav'
        // const isLt2M = file.size / 1024 / 1024 < 10
        if(!extension && !extension2) {
          this.$message({
            message: '上传文件只能是 mp3、wav格式!',
            type: 'warning'
          });
        }
        // if(!isLt2M) {
        //     this.$message({
        //         message: '上传文件大小不能超过 10MB!',
        //         type: 'warning'
        //     });
        // }
        // return extension || extension2 && isLt2M
        return extension || extension2
      },
      /** 上传成功后的回调 */
      uploadSuccess(response, file, fileList) {
        console.log("11112" + response.fileName);
        this.$refs.upload.clearFiles();
        console.log(file);
        this.form.cover = response.fileName
        this.files.path = response.fileName
      },
      /** 上传之前的校验 */
      checkUpload(file) {
        console.log("文件类型", file)
        const imgType = file.type
        //图片不大于2M
        const isLtSize = file.size / 1024 / 1024 < 2
        if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
          this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
          return false;
        }
        if (!isLtSize) {
          this.$message.error(`上传图片大小不能超过2MB!`)
          return false;
        }
      },
      // handleRemove(file,fileList){
      //   console.log(file, fileList);
      //   this.files.path = '';
      //   this.picList = [];
      //   this.form.cover = undefined;
      // },
      /**地图弹框确认获取定位*/
      getCoordinate() {
        if (this.$refs.map.pointInfo.location) {
          this.form.latitude = this.$refs.map.pointInfo.location.lat;
          this.form.longitude = this.$refs.map.pointInfo.location.lng;
          this.form.address = this.$refs.map.pointInfo.address;
          console.log(this.form)
          this.mapDialog = false
        } else {
        }
      },
    }
  };
</script>
<!-- 全局样式 -->
<style scoped>
  .fm-button{
    background-color:#ff6a00;
    border-color:#ff6a00;
  }
  .el-upload__tip {
    line-height: 1.2;
  }

  .avatar-uploader i {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader i:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>

